﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Sitecore.Data.Items;
using Telerik.Web.UI;
using System.Data;
using Workflow.Alerts.DAL;
using workflow.Dal;

namespace Workflow.Alerts.Sublayouts
{
    public partial class Executed : BaseControl, IExecuteView
    {
        bool isPartApproved = false;
        #region IExecuteView Members

        public bool ChangeStatus { get { return String.IsNullOrEmpty(Request.QueryString["save"]); } }

        public String Comments
        {
            get
            {
                return txtComments.Text;
            }
            set
            {
                txtComments.Text = value;
            }
        }

        public Int32 AlertId
        {
            get { return Int32.Parse(Request.QueryString["alertId"]); }
        }

        public DateTime? StartDate
        {
            get
            {
                return rdpStartDate.SelectedDate;
            }
            set
            {
                rdpStartDate.SelectedDate = value;
            }
        }

        public DateTime? EndDate
        {
            get
            {
                return rdpEndDate.SelectedDate;
            }
            set
            {
                rdpEndDate.SelectedDate = value;
            }
        }

        public DataTable ContractorList
        {
            set
            {
                ddlContractors.DataSource = value;
                ddlContractors.DataTextField = "name";
                ddlContractors.DataValueField = "id";
                ddlContractors.DataBind();
            }
        }

        public Int32? Contractor
        {
            get
            {
                if (ddlContractors.SelectedItem == null ||
                    ddlContractors.SelectedItem.Value == "0")
                    return null;
                else
                    return Int32.Parse(ddlContractors.SelectedItem.Value);
            }
            set
            {
                if (value.HasValue)
                {
                    ddlContractors.ClearSelection();
                    ddlContractors.Items.FindByValue(value.ToString()).Selected = true;
                }
            }
        }



        public Int32? AlertArea
        {
            get
            {
                if (String.IsNullOrEmpty(txtArea.Text))
                    return null;
                return Int32.Parse(txtArea.Text);
            }
            set
            {
                txtArea.Text = value.ToString();
            }
        }


        public Boolean IsPartiallyAccepted
        {
            get { return isPartApproved; }
            set { isPartApproved = value; }
        }

        public event OnExecuteLoad ExecuteLoad;

        public event OnExecuteSave ExecuteSave;

        #endregion

        #region Private Methods
        private void ClearSession()
        {
            var keys = Session.Keys.Cast<String>();
            var executeKeys = (from k in keys
                               where k.StartsWith("execute_")
                               select k).ToList<String>();
            foreach (var key in executeKeys)
                Session.Remove(key);

        }

        private bool IsContractorVisible()
        {
            return (CurrentUser.Type == WorkflowEnums.UserType.Municipality &&
                CurrentAlertDetails.UseMunicipConstractor == 1);
        }
        #endregion

        #region Events
        protected void Page_Load(object sender, EventArgs e)
        {
            PresentationManager.RegisterView(typeof(ExecuteViewPresenter), this, new WebSessionProvider());

            if (!IsPostBack && ExecuteLoad != null)
                ExecuteLoad();

            contractor.Visible = IsContractorVisible();
            mgList.SaveChangesInDB = false;

            var isPartiallyApproved = Request.QueryString["part"];
            if (isPartiallyApproved != null)
            {
                isPartApproved = true;
            }
            else
            {
                string classStr = DivGegevens.Attributes["class"];
                if (!string.IsNullOrEmpty(classStr))
                {
                    classStr = classStr.Replace("labelPartApprove", "");
                    DivGegevens.Attributes["class"] = classStr;
                }
            }
        }

        private bool IsAcceptedPartially()
        {
            return (CurrentUser.Type == WorkflowEnums.UserType.Municipality &&
                     ChangeStatus);
        }

        protected void btnClick_Command(object sender, CommandEventArgs e)
        {
            if (ExecuteSave != null && e.CommandName == "Update")
            {
                var listOfMaterials = Session["TempAlertMaterials"] as List<AlertMaterials>;
                if (!listOfMaterials.Where(am => am.Alert.id == AlertId).Any())
                {
                    mgList.ShowMaterialValidator = true;
                }
                else
                {
                    ExecuteSave();
                    phClose.Visible = true;
                    Session[WorkflowConstants.OpenList] = "true";
                }
            }
            else if (e.CommandName == "Cancel")
            {
                mgList.ClearTempValues();
                phClose.Visible = true;
                Session[WorkflowConstants.OpenList] = "true";
            }
        }

        #endregion

        #region Properties
        AlertDetails CurrentAlertDetails
        {
            get { return Session[WorkflowConstants.ExecuteData] as AlertDetails; }
        }
        #endregion

        protected void Page_Init(object sender, EventArgs e)
        {
            mgList.Alert = Request.QueryString["alertId"];
        }
    }
}